<script setup lang="ts">
import ChatNav from "./ChatNav.vue";
import ChatDomain from "./ChatDomain.vue";
import ChatContent from "./ChatContent.vue";
import { userList } from "../api/user.js";
import { getHistorySessionById } from "../api/historySession.js";
import { getContentBySendId } from "../api/content.js";
// import io from "socket.io-client";
import { useMainStore } from "../store/main";
const store = useMainStore();
import Conversition from "../class/Conversition";
import { onMounted, getCurrentInstance, reactive } from "vue";
const { proxy }: any = getCurrentInstance();


const chatUrl: any = import.meta.env.VITE_BASE_API || "ws://chat3.he4966.cn:1819/xiaohe__admin";

const stateData = reactive({
  page: {
    pageIndex: 1,
    pageSize: 30,
  },
  historySessionPage: {
    pageIndex: 1,
    pageSize: 30,
  },
  contentPage: {
    pageIndex: 1,
    pageSize: 30,
  },
  loadUserAll: false,
  loadHistorySessionAll: false,
  loadContentAll: false,
  wsReconnectAttempts: 0,
  wsReconnectInterval: 3000,
  wsMaxReconnectAttempts: 10,
  heartbeatTimer: null as any,//用于存储心跳定时器
  heartbeatInterval: 10000, // 10秒发送一次心跳

});

onMounted(() => {
  // alert('初始化页面');
  init();
});

async function init() {
  if (proxy.$commom.isLogin()) {
    initSocket();
    getUserList();
    getHistorySession();
    getContent();
  } else {
    proxy.$router.replace({
      name: "Home",
    });
  }
}

// 匹配地址栏参数
function GetQueryString(name: string) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

// 获取用户列表
function getUserList() {
  let query = {
    id: store.sender?.Id,
    pageIndex: stateData.page.pageIndex,
    pageSize: stateData.page.pageSize,
  };
  userList(query).then((res: any) => {
    if (res?.code > 0) {
      store.allSessionList.push(...res?.data);
      if (res?.data.length < stateData.page.pageSize) {
        stateData.loadUserAll = true;
      } else {
        stateData.page.pageIndex += 1;
        getUserList();
      }
    } else {
      proxy.$message.error(res?.message);
    }
  });
}

function getHistorySession() {
  let query = {
    id: store.sender?.Id,
    pageIndex: stateData.historySessionPage.pageIndex,
    pageSize: stateData.historySessionPage.pageSize,
  };
  getHistorySessionById(query).then((res: any) => {
    if (res?.code > 0) {
      store.sessionList.push(...res?.data);
      if (res?.data.length < stateData.historySessionPage.pageSize) {
        stateData.loadHistorySessionAll = true;
      } else {
        stateData.historySessionPage.pageIndex += 1;
        getHistorySession();
      }
    } else {
      proxy.$message.error(res?.message);
    }
  });
}

function getContent() {
  let query = {
    id: store.sender?.Id,
    pageIndex: stateData.contentPage.pageIndex,
    pageSize: stateData.contentPage.pageSize,
  };
  getContentBySendId(query).then((res: any) => {
    if (res?.code > 0) {
      store.conversitionList.push(...res?.data);
      if (res?.data.length < stateData.contentPage.pageSize) {
        stateData.loadContentAll = true;
      } else {
        stateData.contentPage.pageIndex += 1;
        getContent();
      }
    } else {
      proxy.$message.error(res?.message);
    }
  });
}

function initSocket() {

  // store.ws = new WebSocket(chatUrl + store.sender.Url + "__admin");
  // store.ws.onopen = () => {
  //   console.log("连接成功");
  //   const joinChatMessage = {
  //     SendId: store.sender.Id,
  //     SendName: store.sender.Name,
  //     ReviceId: -1,
  //     ReviceName: "",
  //     NoCode: store.noCode,
  //   };
  //   store.ws.send(JSON.stringify(joinChatMessage));
  // };


  // store.ws.onclose = () => {
  //   console.log("连接已断开");
  //    // 尝试重连
  //    if (stateData.wsReconnectAttempts < stateData.wsMaxReconnectAttempts) {
  //       stateData.wsReconnectAttempts++;
  //       console.log(`尝试第 ${stateData.wsReconnectAttempts} 次重连...`);
  //       setTimeout(connect, stateData.wsReconnectInterval);
  //     } else {
  //       console.log("达到最大重连次数，停止重连");
  //       proxy.$message.error("WebSocket连接失败，请刷新页面重试");
  //     }
  // };
  function connect() {
    store.ws = new WebSocket(chatUrl + store.sender.Url + "__admin");

    store.ws.onopen = () => {
      console.log("连接成功");
      // 重置重连次数
      stateData.wsReconnectAttempts = 0;
      const joinChatMessage = {
        SendId: store.sender.Id,
        SendName: store.sender.Name,
        ReviceId: -1,
        ReviceName: "",
        NoCode: store.noCode,
      };
      store.ws.send(JSON.stringify(joinChatMessage));

      // 启动心跳
      startHeartbeat();
    };

    store.ws.onclose = () => {
      console.log("连接已断开");
      // 清除心跳定时器
      clearHeartbeat();
      // 尝试重连
      if (stateData.wsReconnectAttempts < stateData.wsMaxReconnectAttempts) {
        stateData.wsReconnectAttempts++;
        console.log(`尝试第 ${stateData.wsReconnectAttempts} 次重连...`);
        setTimeout(connect, stateData.wsReconnectInterval);
      } else {
        console.log("达到最大重连次数，停止重连");
        proxy.$message.error("WebSocket连接失败，请刷新页面重试");
      }
    };

    // ... 其他现有的 WebSocket 事件处理程序 ...


    store.ws.onmessage = (event: MessageEvent) => {
      console.log("接收到消息", event.data);
      const data = JSON.parse(event.data);

      switch (data.message_type) {
        case "changMsgState":
          store.conversitionList.forEach((x: Conversition) => {
            if (x.NoCode != null && x.NoCode == data.NoCode) {
              x.State = 1;
            }
          });
          break;
        case "joinSuccess":
          store.sender.OnlineState = true;
          // store.conversitionList = data.conversition;
          break;
        case "reviceMsg":
          const message: Conversition = data;
          console.log('reviceMsg', message);
          console.log('message.ReciverId', message.ReciverId, 'store.sender.Id', store.sender.Id);
          if (message.ReciverId == store.sender.Id) {
            store.playMusic();
            if (window.Notification && Notification.permission !== "denied") {
              Notification.requestPermission(function (status) {
                let n = new Notification("HasChat消息通知", {
                  body: "你有一条新的消息",
                });
              });
            }
            for (let item of store.sessionList) {
              let id = item?.FormId || item?.Id;
              if (id == message.ReciverId) {//&& store.sessionSelectId == message.ReciverId
                message.ReadFlag = true;// 将消息的 ReadFlag 属性设置为 true，表示该消息已被阅读。
                //构建更改消息阅读状态的对象
                const changeMsgReadMessage = {
                  SendId: message.ReciverId,
                  ReciverId: store.sender.Id,
                };
                console.log("changeMsgReadMessage", changeMsgReadMessage);

                store.ws.send(JSON.stringify({ type: "changeMsgRead", message: changeMsgReadMessage }));
                break;
              }
            }
          }
          store.sendLocal(message);
          let len =
            store.sessionList.filter((x: any) => {
              let id = x?.FormId || x.Id;
              return id == message.SendId;
            })?.length ?? 0;
          if (len === 0) {
            let item = store.allSessionList.find((x: any) => x.Id == message.SendId);
            console.log('item', item);
            // if(item==null){
            //   item = new User(message.SendId, item.Name, 0, item.Code, item.Mobile, item.NickName, item.Avatar,item.Url);
            // }
            let session = {
              FormId: item.Id,
              Name: item.Name,
              NickName: item.NickName,
              PersonalitySign: item.PersonalitySign,
              Mobile: item.Mobile,
              Region: item.Region,
              Avatar: item.Avatar,
              Email: item.Email,
              ById: store.sender.Id,
            };
            console.log('session', session);
            store.sessionList.push(session);
          }
          store.toBottom();
          break;
        case "squeezeOut":
          if (data.noCode == store.noCode) {
            store.logout();
            alert("账户在其他地方登陆，会话已断开");
            proxy.$router.replace({
              name: "Home",
            });
          }
          break;

        case "error":

          alert(data.msg);
          proxy.$router.replace({
            name: "Home",
          });

          break;
        default:
          console.log("未知的消息类型:", data);
      }
    };

    store.ws.onerror = (error: Event) => {
      console.error("WebSocket 错误:", error);
    };
    //多设备在线时，强制旧设备下线
    // store.ws.on("squeezeOut", (data: any) => {
    //   if (data.noCode == store.noCode) {
    //     store.logout();
    //     alert("账户在其他地方登陆，会话已断开");
    //     proxy.$router.replace({
    //       name: "Home",
    //     });
    //   }
    // });

  }


  // 心跳相关函数
  function startHeartbeat() {
    clearHeartbeat(); // 清除可能存在的旧定时器
    stateData.heartbeatTimer = setInterval(() => {
      if (store.ws && store.ws.readyState === WebSocket.OPEN) {
        // 发送心跳消息
        store.ws.send(JSON.stringify({ type: "heartbeat", timestamp: Date.now() }));
      }
    }, stateData.heartbeatInterval);
  }

  function clearHeartbeat() {
    if (stateData.heartbeatTimer) {
      clearInterval(stateData.heartbeatTimer);
      stateData.heartbeatTimer = null;
    }
  }

  connect(); // 初始化连接
}
</script>

<template>
  <div class="chat">
    <chat-nav />
    <chat-domain />
    <chat-content />
  </div>
</template>

<style scoped lang="less">
.chat {
  width: 100%;
  height: 100%;
  display: flex;
  border-radius: 33px;
}
</style>
